const marked = require('marked')
const {remote, ipcRenderer} = require('electron')
const mainProcess = remote.require('./main') // 用镜像引入主进程
const markdownView = document.querySelector('#markdown')
const htmlView = document.querySelector('#html')
const newFileButton = document.querySelector('#new-file')
const openFileButton = document.querySelector('#open-file')
const saveMarkdownButton = document.querySelector('#save-markdown')
const revertButton = document.querySelector('#revert')
const saveHtmlButton = document.querySelector('#save-html')
const showFileButton = document.querySelector('#show-file')
const openInDefaultButton = document.querySelector('#open-in-default')
let timer = null
const renderMarkdownToHtml = markdown => {
  htmlView.innerHTML = marked(markdown, { sanitize: true })
}

markdownView.addEventListener('keyup', (e) => {
  timer = null
  timer = setTimeout(() => {
    const currentContent = e.target.value
    renderMarkdownToHtml(currentContent)
  }, 1000)
})

openFileButton.addEventListener('click', () => {
  mainProcess.getFileFromUser()
  ipcRenderer.on('file-opened', (e, file, content) => {
    markdownView.value = content;
    renderMarkdownToHtml(content)
  })
})